let socket = null;

let uuid = "";
let isLogin = 0;
connectWebsocket();
//连接websocket
function connectWebsocket() {
    if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        console.log("您的浏览器支持WebSocket");
        let token = localStorage.getItem("token");
        uuid = localStorage.getItem("uuid");
        isLogin = 0;
        //生成随机数
        if (isNull(token)){
            if (isNull(uuid)){
                uuid = getUuid();
                localStorage.setItem("uuid",uuid);
            }
        }else {
            isLogin = 1;
            uuid = token;
        }
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        var reqUrl = WS_HOST + "websocket/0/" + isLogin + "/" + uuid;
        socket = new WebSocket(reqUrl);
        //打开事件
        socket.onopen = function () {
            console.log("Socket 已打开");
        };
        //获得消息事件
        socket.onmessage = function (msg) {
            // console.log("onmessage--" + msg.data);
            let info = JSON.parse(msg.data);
            if (info.type == 0){//新建聊天
                $("#kfName").html("亚联通信-"+info.kfName);
                localStorage.setItem("chatId",info.chatId);
                let li = "<li class=\"clearfix magBox leftMsg\">\n" +
                    "                            <p class=\"leftName\">亚联通信—"+info.kfName+"</p>\n" +
                    "                            <div class=\"msgDiv\">\n" +
                    "                                <div class=\"msgText\"><p>"+info.msg+"</p></div>\n" +
                    "                            </div>\n" +
                    "                        </li>";
                $("#chatPanelList").append(li);
                dibu();
            }else if (info.type == 1){
                $("#kfName").html("亚联通信-"+info.kfName);
                localStorage.setItem("chatId",info.chatId);
                getInitChatInfo(info.chatId,info.kfName);
            }else if (info.type == 2){
                let li = "<li class=\"clearfix magBox leftMsg\">\n" +
                    "                            <p class=\"leftName\">亚联通信—"+info.kfName+"</p>\n" +
                    "                            <div class=\"msgDiv\">\n" +
                    "                                <div class=\"msgText\"><p>"+info.msg+"</p></div>\n" +
                    "                            </div>\n" +
                    "                        </li>";
                $("#chatPanelList").append(li);
                dibu();
            }
            //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        socket.onclose = function () {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }

        //离开页面时，关闭socket
        //jquery1.8中已经被废弃，3.0中已经移除
        // $(window).unload(function(){
        //     socket.close();
        //});
    }
}

//发送消息
function sendMessage(message){
    if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        let msg = {"type": 2, "msgType": 1, "chatId": localStorage.getItem("chatId"), "msg": message};
        // console.log(msg);
        socket.send(JSON.stringify(msg));
    }
}

//获取聊天记录
function getInitChatInfo(chatId,kfName) {
    $.ajax({
        url:LT_HOST+"chat/getChatDetailByChatId"
        ,type:"get"
        ,beforeSend:function(xhr){
            xhr.setRequestHeader('token',layui.data('local_store').token);
        }
        ,data:{
            "chatId":chatId,
            "type":1
        }
        ,contentType: 'application/json'
        ,success:function (res) {
            if (res.code == 200){
                let chatDetail = res.data;
                let li = "<li class=\"clearfix magBox leftMsg\">\n" +
                    "                            <p class=\"leftName\">亚联通信—"+kfName+"</p>\n" +
                    "                            <div class=\"msgDiv\">\n" +
                    "                                <div class=\"msgText\"><p>"+"您好，请问有什么可以帮到您！"+"</p></div>\n" +
                    "                            </div>\n" +
                    "                        </li>";
                $("#chatPanelList").append(li);
                if (chatDetail.length > 0){
                    for (let i = 0; i < chatDetail.length; i++) {
                        if (chatDetail[i].msgType == 0){
                            let li = "<li class=\"clearfix magBox leftMsg\">\n" +
                                "                            <p class=\"leftName\">亚联通信—"+kfName+"</p>\n" +
                                "                            <div class=\"msgDiv\">\n" +
                                "                                <div class=\"msgText\"><p>"+chatDetail[i].kmsg+"</p></div>\n" +
                                "                            </div>\n" +
                                "                        </li>";
                            $("#chatPanelList").append(li);
                        }else if (chatDetail[i].msgType == 1){
                            let li = "<li class=\"clearfix magBox rightMsg\">\n" +
                                "                            <div class=\"msgDiv\">\n" +
                                "                                <div class=\"msgText\">"+chatDetail[i].umsg+"</div>\n" +
                                "                            </div>\n" +
                                "                        </li>";
                            $("#chatPanelList").append(li);
                        }
                    }
                }
                dibu();
            }
        }
        ,error:function () {
            console.log("ajax error");
        }
    });
}

//关闭页面
function closePage() {
    parent.hideKf();
    socket.close();
}